package com.ddm.mapper;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ddm.entity.vxEntity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * <p>
 *  Mapper 接口
 * </p>
 *
 * @author horizon
 * @since 2025-01-17
 */
@Mapper
public interface UserMapper extends BaseMapper<User> {
    /**
     * 获取用户类型
     */
    @Select("SELECT user_type FROM user WHERE id = #{id}")
    Integer selectUserTypeById(Long id);

    @Select("SELECT * FROM user WHERE user_name = #{username}")
    User findByUsername(String username);

    @Select("SELECT * FROM user WHERE email = #{email}")
    User findByEmail(String email);

    @Select("SELECT * FROM user WHERE phone_num = #{phoneNum}")
    User findByPhoneNum(String phoneNum);

    // 1. 对应 XML 中的 selectUserByIdForUpdate 标签
    User selectUserByIdForUpdate(long userId);

    /**
     * 联表查询用户完整信息
     * 关联user_base和user表，通过id字段关联
     */
//    @Select("""
//        SELECT
//            u.id,
//            u.user_name,
//            u.email,
//            u.phone_num,
//            ub.reg_time,
//            ub.last_login,
//            ub.is_active,
//            u.photo_url,
//            u.user_type,
//            u.openid,
//            u.create_time
//        FROM
//            user_base ub
//        LEFT JOIN
//            user u ON ub.id = u.id
//        WHERE
//            ub.id = #{id} AND u.deleted = 0
//    """)
//    @Results({
//            // user_base表字段映射
//            @Result(property = "id", column = "id"),
//            @Result(property = "username", column = "user_name"),
//            @Result(property = "email", column = "email"),
//            @Result(property = "phone", column = "phone_num"),
//            @Result(property = "regTime", column = "reg_time"),
//            @Result(property = "lastLogin", column = "last_login"),
//            @Result(property = "isActive", column = "is_active"),
//            // user表字段映射
//            @Result(property = "photoUrl", column = "photo_url"),
//            @Result(property = "userType", column = "user_type"),
//            @Result(property = "openid", column = "openid"),
//            @Result(property = "createTime", column = "create_time")
//    })
//    UserInfoVO selectUserInfoById(Integer id);



    /**
     * 根据ID查询user表信息（排除已删除用户）
     */
    @Select("SELECT * FROM user WHERE id = #{id} AND deleted = 0")
    User selectUserById(Long id);

    /**
     * 更新user表信息
     */
    @Update("""
    <script>
        UPDATE user 
        <set>
            <!-- 每个字段都加非空判断：只有 User 对象中该字段不为 null 才更新 -->
            <if test="userName != null">user_name = #{userName},</if>
            <if test="userType != null">user_type = #{userType},</if>
            <if test="email != null">email = #{email},</if>
            <if test="phoneNum != null">phone_num = #{phoneNum},</if>
             <if test="photoUrl != null">photo_url = #{photoUrl},</if>
        </set>
        WHERE id = #{id} AND deleted = 0
    </script>
""")
    int updateUser(User user);

    /**
     * 更新密码（操作user表的password字段）
     */
    @Update("""
        UPDATE user
        SET password = #{newPassword} 
        WHERE id = #{userId} AND password = #{oldPassword}
    """)
    int updatePassword(@Param("userId") long userId,
                       @Param("oldPassword") String oldPassword,
                       @Param("newPassword") String newPassword);

    /**
     * 检查密码是否正确
     */
    @Select("SELECT COUNT(1) FROM user WHERE id = #{userId} AND password = #{password}")
    int checkPassword(@Param("userId") Integer userId, @Param("password") String password);

    /**
     * 查询所有用户
     */
    List<User> selectAllWithDeleted();
    // 分页查询所有用户（包括已删除），支持条件筛选
    IPage<User> selectAllWithCondition(Page<User> page, @Param(Constants.WRAPPER) Wrapper<User> queryWrapper);
}
